package com.zhuyi.broadcast.config;

import com.zhuyi.broadcast.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private WebSocketService webSocketService;  // 注入 WebSocketService

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 注册 WebSocket 端点，并配置相关设置
        registry.addHandler(myWebSocketHandler(), "/ws")
                .setAllowedOrigins("*");  // 设置允许跨域请求的来源
    }

    // 创建一个 WebSocketHandler，使用 Spring 管理依赖注入
    public WebSocketHandler myWebSocketHandler() {
        return new WebSocketHandlerImpl(webSocketService);  // 传递 WebSocketService
    }

    // WebSocket 处理器类
    private static class WebSocketHandlerImpl extends TextWebSocketHandler {
        private final WebSocketService webSocketService;

        public WebSocketHandlerImpl(WebSocketService webSocketService) {
            this.webSocketService = webSocketService;
        }

        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            // 连接建立后，添加会话
            webSocketService.addSession(session);
        }

        @Override
        protected void handleTextMessage(WebSocketSession session, org.springframework.web.socket.TextMessage message) throws Exception {
            // 处理收到的消息
            webSocketService.handleMessage(message.getPayload(), session);
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
            // 连接关闭后，移除会话
            webSocketService.removeSession(session);
        }
    }
}
